package me.hys.service.system.impl;

import java.util.List;
import java.util.Map;

import me.hys.base.ApiResult;
import me.hys.cons.ApiStatus;
import me.hys.dao.system.IDeviceTokenMapper;
import me.hys.entity.system.DeviceTokenEntity;
import me.hys.kits.ApnsKit;
import me.hys.kits.CollectionKit;
import me.hys.kits.StrKit;
import me.hys.service.system.IDeviceTokenManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Author: @author HYS . <br>
 * Date: 2015-10-19 下午10:56:46 . <br>
 * Function:
 */
@Service
@Transactional
class DeviceManagerImpl implements IDeviceTokenManager {
	@Autowired
	private IDeviceTokenMapper deviceTokenMapper;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * me.hys.service.system.IDeviceTokenManager#findByDeviceToken(java.lang
	 * .String)
	 */
	@Override
	public DeviceTokenEntity findByDeviceToken(String deviceToken) {
		return deviceTokenMapper.findByDeviceToken(deviceToken);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.service.system.IDeviceTokenManager#push(java.lang.String,
	 * java.util.Map)
	 */
	@Override
	public void push(final String content, final Map<String, Object> params) {
		int total = deviceTokenMapper.findAllCount();
		final int page = (int) Math.ceil(total * 1.0f / 50);
		final ApnsKit apsnKit = ApnsKit.getInstance();
		// 避免主线程阻塞
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int start = 0; start < page; start++) {
					List<String> deviceTokens = deviceTokenMapper
							.findAll(start);
					if (!CollectionKit.isNull(deviceTokens)) {
						for (String deviceToken : deviceTokens) {
							apsnKit.push(deviceToken, content, params);
						}
					}
				}
			}
		}).start();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see me.hys.service.system.IDeviceTokenManager#save(java.lang.String)
	 */
	@Override
	public ApiResult save(DeviceTokenEntity entity) {
		ApiResult apiResult = new ApiResult(ApiStatus.FAILED);
		if (StrKit.isBlank(entity.getDeviceToken())) {
			apiResult.setMsg("设备号不能为空");
			return apiResult;
		}
		if (null == deviceTokenMapper
				.findByDeviceToken(entity.getDeviceToken())) {
			deviceTokenMapper.save(entity);
			apiResult.setResult(ApiStatus.SUCCESS);
			apiResult.setMsg("操作成功");
		} else {
			deviceTokenMapper.update(entity);
			apiResult.setResult(ApiStatus.SUCCESS);
			apiResult.setMsg("更新成功");
		}
		return apiResult;
	}

}
